class Solution {
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    int m, n;
    int[][] memo;
    public int longestIncreasingPath(int[][] matrix) {
        m = matrix.length;
        n = matrix[0].length;
        memo = new int[m][n];
        int sum = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                sum = Math.max(dfs(matrix, i, j), sum);
            }
        }
        return sum;
    }
    int dfs(int[][] matrix, int i, int j) {
        if(memo[i][j] != 0) {
            return memo[i][j];
        }

        int count = 1;
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) {
                count = Math.max(dfs(matrix, x, y) + 1, count);
            }
        }
        memo[i][j] = count;
        return count;
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] arr = {{9,9,4},{6,6,8},{2,1,1}};
        solution.longestIncreasingPath(arr);
    }
}